﻿using System;
using System.Web;
using System.Collections;
using System.Web.Caching;

namespace SCCN.Utility
{
    /// <summary>
    /// .net数据缓存帮助类,用于操作对对象进行缓存的方法集合
    /// </summary>
    public class CacheHelper
    {

        #region 设置Cache缓存

        /// <summary>
        /// 设置数据缓存
        /// </summary>
        /// <param name="cacheKey">缓存键名</param>
        /// <param name="objObject">缓存对象</param>
        public static void SetCache(string cacheKey, object objObject)
        {
            System.Web.Caching.Cache objCache = HttpRuntime.Cache;
            objCache.Insert(cacheKey, objObject);
        }

        /// <summary>
        /// 设置数据缓存
        /// </summary>
        /// <param name="cacheKey">缓存键名</param>
        /// <param name="objObject">缓存对象</param>
        /// <param name="expiredMinute">过期时间（分钟为单位）</param>
        public static void SetCache(string cacheKey, object objObject, double expiredMinute)
        {
            System.Web.Caching.Cache objCache = HttpRuntime.Cache;
            objCache.Insert(cacheKey, objObject, null, DateTime.Now.AddMinutes(expiredMinute), Cache.NoSlidingExpiration, System.Web.Caching.CacheItemPriority.NotRemovable, null);
        }

        /// <summary>
        /// 设置数据缓存
        /// </summary>
        /// <param name="cacheKey">缓存键名</param>
        /// <param name="objObject">缓存对象</param>
        /// <param name="absoluteExpiration">绝对到期时间（强制移除缓存内容）</param>
        /// <param name="slidingExpiration">最后一次访问缓存对象与对象到期时间的间隔</param>
        public static void SetCache(string cacheKey, object objObject, DateTime absoluteExpiration, TimeSpan slidingExpiration)
        {
            System.Web.Caching.Cache objCache = HttpRuntime.Cache;
            objCache.Insert(cacheKey, objObject, null, absoluteExpiration, slidingExpiration);
        }

        #endregion

        #region 获取缓存值
        /// <summary>
        /// 获取指定键数据缓存值
        /// </summary>
        /// <param name="CacheKey">缓存键名</param>
        /// <returns>返回缓存值</returns>
        public static Object GetCache(string cacheKey)
        {
            System.Web.Caching.Cache objCache = HttpRuntime.Cache;
            return objCache.Get(cacheKey); 
        }

        #endregion

        /// <summary>
        /// 移除指定数据缓存
        /// </summary>
        public static void RemoveAllCache(string cacheKey)
        {
            System.Web.Caching.Cache _cache = HttpRuntime.Cache;
            _cache.Remove(cacheKey);
        }

        /// <summary>
        /// 移除全部缓存
        /// </summary>
        public static void RemoveAllCache()
        {
            System.Web.Caching.Cache _cache = HttpRuntime.Cache;
            IDictionaryEnumerator CacheEnum = _cache.GetEnumerator();
            while (CacheEnum.MoveNext())
            {
                _cache.Remove(CacheEnum.Key.ToString());
            }
        }
    }
}
